<?php

session_start();

if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
    $login = "";
    header("Location: login.php");
} else {
    $login = $_SESSION['login'];
}

$errorMessage = "";
$num_rows = 0;
$used = "";

include 'i_functions.php';


if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $csvFile = $_POST["csvFile"];
    $TableName = $_POST["TableName"];
    $csvCount = $_POST['csvCount'];
    $csvCol = $_POST['csvCol'];
    $MapTo = $_POST['MapTo'];
    $TableCol = $_POST['TableCol'];
    $UserExit = $_POST['UserExit'];
    var_dump($TableCol);
    print "<br>";
    var_dump($UserExit);
    print "<br>";
    $MapToCol = array();
    //print "<br>" . $csvCount . " columns to map<br>";

    $user_name = "root";
    $pass_word = "haddons";
    $database = "PPI";
    $server = "127.0.0.1";

    $db_handle = mysql_connect($server, $user_name, $pass_word);
    $db_found = mysql_select_db($database, $db_handle);

    if ($db_found) {
        /* $sql = "LOAD DATA INFILE '" . $csvFile . "' IGNORE ";
          $sql = $sql . " INTO TABLE `" . $TableName . "`";
          $sql = $sql . " FIELDS TERMINATED BY ','";
          $sql = $sql . " LINES TERMINATED BY '\\n'";
          $sql = $sql . " IGNORE 1 LINES ("; */
        print "<br>";
        for ($i = 0; $i < $csvCount; $i++) {
            //if ($csvCol[$i] <> "") {
                $ColName = $TableCol[$MapTo[$i]];
                $UE = $UserExit[$MapTo[$i]];
                print $ColName . "-" . $UE . ",";
                $MapToCol[$i] = $ColName;
                $MapToUE[$i] = $UE;
                if ($ColName == "") {
                    $ColName = "@ignore";
                }
                /* $sql = $sql . "`" . $ColName . "`";
                  if ($i < ($csvCount - 1)) {
                  $sql = $sql . ", ";
                  } */
            //}
        }
        //$sql = $sql . " )";
        //$sql = $sql .
        //print "<br>" . $sql . "<br>";
// save mapping
        $x = explode(".", $csvFile);
        $x = explode("/", $x[0]);
        $mapID = $x[1] . "_to_" . $TableName;
        $mapcsv = implode(",", $csvCol);
        //$mapTbl = implode(",", $MapToCol);
        $mapTo = implode(",", $MapTo);
        $mapTbl = implode(",", $TableCol);
        $mapUE = implode(",", $UserExit);
        $mapSQL = "INSERT INTO `PPI`.`csv_map`
            (`ID`, `csvFile`, `TableName`, `csvCol`, `MapTo`, `TableCol`, `UserExits`)
            VALUES ( '$mapID', '$csvFile', '$TableName', '$mapcsv', '$mapTo', '$mapTbl', '$mapUE')";
            //VALUES ( '$mapID', '$csvFile', '$TableName', '$mapcsv', '$mapTbl', '$mapUE')";
        print "<br>" . $mapSQL;
        $result = mysql_query($mapSQL);
        print "<br>result=" . $result;
        //
        mysql_close($db_handle);
    }
}
?>